 (function($) {

$.news = {};

$.news.suggest = {};

$.news.suggest.window = null;

$.news.suggest.tags = null;

$.news.prepare = function()
{
	$.news.elementTemplate = $("#newElementTemplate").clone();
	
	$.news.commentTemplate = $("#newElementCommentTemplate").clone();
	
	$.news.newElementShowAllTemplate = $("#newElementShowAllTemplate").clone();
	
	$("#newElementTemplate").remove();
	
	$("#newElementCommentTemplate").remove();
	
	$("#newElementShowAllTemplate").remove();
	
	$.news.suggest.prepare();
	
	$("#scrollableAreaContent").scroll(function(t)
	{
		var elem = $('#scrollableAreaContent');
		
		var inner = $('#scrollableAreaContent> #newElementsArea');
		
		if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= inner.outerHeight() ) 
		 {
			$.news.loadNewElements (0);
		 }
	});
	
	$("#btnStartCreateNewElement").click(function()
	{
		$("#createElementsStart").animate({ height: 'hide', opacity:0 }, 'fast');
		$("#SuggestElementsInputElements").animate({ height: 'show', opacity:1 }, 'fast');
	});

	$("#btnStartCreateNewElement").click(function()
	{
		$("#createElementsStart").animate({ height: 'hide', opacity:0 }, 'fast');
		$("#SuggestElementsInputElements").animate({ height: 'show', opacity:1 }, 'fast');
	});
	
	$("#btnStartCreateNewElement").click(function()
	{
		$("#createElementsStart").animate({ height: 'hide', opacity:0 }, 'fast');
		$("#SuggestElementsInputElements").animate({ height: 'show', opacity:1 }, 'fast');
	});
	
	$.news.loadNewElements();
	
	setInterval($.news.refresh, 2000);	
}

$.news.suggestNewElement = function($t)
{

	if((!$("#SuggestElementsAread1").attr('elementId') > 0) ||
		(!$("#SuggestElementsAread2").attr('elementId') > 0) ||
		($("#newElementName").val().length == 0) ||
		($("#newElementInputTags").val().length == 0))
	{
		$("#elementsReturnMessage")
			.text("Please fill both fields.")
			.dialog(
			{
				close: function()
				{
					$t.focus();
				}
			});
		return;
	}

	var query = "e1=" + $("#SuggestElementsAread1").attr('elementId') + 
						"&e2=" + $("#SuggestElementsAread2").attr('elementId') +
						"&name=" + $("#newElementName").val() + 
						"&tags=" + $("#newElementTags").val();
						
	$.post("./bus/new_element.php", query, function(data)
	{
		$("#SuggestElementsAreaIcon").click();
		$("#SuggestElementsAread1").attr('elementId', 0).text("");
		$("#SuggestElementsAread2").attr('elementId', 0).text("");
		$("#newElementName").val("");
		$("#newElementInputTags").val("");
	})
}

$.news.loadNewElements = function(direction)
{
	if(direction == 'clear')
	{
		$.news.newerCombinationId=0;
		$.news.olderCombinationId=0;
		$(".newElement", "#newElementsArea").remove();
		$.news.loadNewElements(0);
		return;
	}

	if(!direction)
		direction = 0
		
	if(!$.news.olderCombinationId)
		$.news.olderCombinationId = 0;
		
	if(!$.news.newerCombinationId)
		$.news.newerCombinationId = 0;

	$.post("./bus/load_new_elements.php", 
		"olderCombinationId=" + $.news.olderCombinationId +
		"&newerCombinationId=" + $.news.newerCombinationId + 
		"&direction=" + direction,
	function(data)
	{
		if(data.Elements && $.news.newerCombinationId < data.Elements[0].CombinationId)
			$.news.newerCombinationId = data.Elements[0].CombinationId;
	
		for(var item in data.Elements)
		{
			$.news.createNewElement(data.Elements[item], direction);
			
			if($.news.olderCombinationId==0 || $.news.olderCombinationId > data.Elements[item].CombinationId)
				$.news.olderCombinationId = data.Elements[item].CombinationId;
		}
	});
}

$.news.createNewElement = function(element, direction)
{

	var $clone = $(".newElement[combinationId=" +element.CombinationId+"]");
	
	
	
	if($clone.length == 0)
	{	
		$clone = $.news.elementTemplate.clone();
		
		$clone.attr('combinationId', element.CombinationId);
		
		if(direction == 0)
		{
			$("#scrollableAreaContentBottomPlaceholder").before($clone);
			
			$clone.animate({ height: 'show', opacity:1 }, 'fast');
		}
		else
		{
			$("#newElementsArea").prepend($clone);
			
			$clone.animate({ height: 'show' , opacity:1 }, 'fast');
		}
		
		if(element.Votes.AuthorId == $.cookie('Id'))
			$(".button", $clone).addClass("ui-state-active"); 
			
		$("textarea", $clone).keypress(function(e)
		{
			if(e.which == 13)
			{
				$.news.Comment($(this), element.CombinationId);
				e.preventDefault();
			}
		}).enableSelection();
		
		$clone.disableSelection();
		
		$(".button", $clone).click(function()
		{
				$.news.Vote(element, $(this));
		});
	}
	
	$clone.attr('invalidate', 0);

	//newElementPic
	$("#newElementTime", $clone).html($.createdAt(element.CreateDate))	;
	$("#newElementUserName", $clone).html(element.UserName);
	
	//elements = element.ElementId
	//TODO:Wow it
	var msg = "Thinks [" + element.Elements.Name[0] + "] with [" + element.Elements.Name[1] + "] gives [" + element.ProductName + "].";	
	
	$("#newElementMessage", $clone).html(msg);
	
	//TODO:$("#newElementTags", $clone).html(element.UserName);
	msg = "Be the first to vote.";
	
	if(element.Votes.Value == 0)
		msg = element.Votes.Name + " up this.";
	else if 	(element.Votes.Value > 0)
		msg = element.Votes.Name + " and " + element.Votes.Value + " more up this.";
	
	$("#newElementUpers", $clone).html(msg);

	for(var i=0;i<element.Comments.length;i++)
	{
		if(element.Comments.length > 3)
		{
			if(i > 1 && i<element.Comments.length-1)
			{
				
				if(i < 5)
				{
					$.news.createNewElementComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'collapse');
				}
				else
				{
					$.news.createNewElementComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'hide');
				}
				
			}
			else
				$.news.createNewElementComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'show');
		}
		
	}
}

$.news.Vote = function(element, $t)
{

	var query = "combinationId=" + element.CombinationId +
		"&vote=1";

	$.post("./bus/new_comment.php", query, function(data)
	{
		if(data.sucess)
		{
		
			if(data.msg == "down")
			{
				$t.removeClass("ui-state-active");
				
				$("#newElementUpers", $t.parent()).html("You un-up this.");
				
				return;
			}
			else
			{
				$("#newElementUpers", $t.parent()).html("You up this.");
				
				$t.addClass("ui-state-active"); 
			}

			data.Vote.Name = $.cookie("Name");
			data.Vote.CreateDate = 0;
		}			
	});
}

$.news.Comment = function($t, combinationId, voteId)
{
	if(!voteId)
		voteId = 0;

	if($t.val().length == 0 && voteId == 0)
		return;

		
	var query = "combinationId=" + combinationId +
		"&voteId=" + voteId +
		"&message=" + $t.val();
		
	$.post("./bus/new_comment.php", query, function(data)
	{
		if(data.sucess)
		{
			if(voteId == 0)
			{
				data.Vote.Name ="Me";
				data.Vote.CreateDate = 0;
				data.Vote.AuthorId = $.cookie('Id');
			
				$.news.createNewElementComment(data.Vote, $t.parent().parent().parent(), combinationId, data.Vote.Id);
				
				$t.val('');
			}
			
			if(data.delete == "delete")
			{
				$t.parent().parent().animate({ height: 'hide', opacity:0 }, 'fast');
			}
		}
	});
}

$.news.createNewElementComment = function(comment, $newElement, combinationId, voteId, mode)
{
	var $clone = $(".newElementComment[voteId=" +voteId+"]");
	
	if($clone.length == 0)
	{	
		$clone = $.news.commentTemplate.clone();
		
		$clone.attr('voteId', voteId);
		
		if(mode == 'hide')
			$clone.css('display', 'none').attr('mode', 'collapse');
		
		$("#newElementCommentContent:last", $newElement).before($clone);
	
		if(mode == 'collapse')
		{
			$clone.css('height', '8').
			css('overflow', 'hidden').
			css('cursor', 'pointer').
			attr('mode', 'collapse').
			css('margin-left', 2).
			click(function()
			{
				$(".newElementComment[mode=collapse], .newElementComment[mode=hide]",  $newElement).
					hide().
					css('height', '').
					css('margin-left', '').
					css('cursor', '').
					animate({height:'show', opacity: 1, }, 'fast').
					unbind('click');
			});
			
		}

		if(mode != 'hide')
			$clone.animate({height:'show', opacity: 1}, 'fast');
			
	
		if(comment.AuthorId == $.cookie('Id'))
		{
			$("#newElementCommentMessage", $clone).click(function()
			{
				var $label = $(this);
				
				$textarea = $("<textarea>");
				
				$textarea.hide().css('min-height', 40);
				
				$t = $(this);
				
				$textarea.css('height', $label.height());
				
				$t.after($textarea);
				
				$(this).parent().css('min-height', $(this).parent().height());
				
				$(this).animate({ height: 'hide', opacity: 0}, 'fast');	
				$textarea.animate({ height: 'show', opacity: 1}, 'fast');
				
					$textarea.val($(this).text())
					.keypress(function(e, t)
					{
						if(e.which == 13)
						{
							$(this).TextMask();
							$.news.Comment($(this), combinationId, voteId);
							
							$label.html($(this).val());
							$(this).animate({ height: 'hide', opacity: 0}, 'fast');
							$label.animate({ height: 'show', opacity: 1}, 'fast');
							e.preventDefault();
						}

					})
					.TextMask(null, "Remove comment")
					.blur(function(e, t)
					{
					//	$label.html($(this).val());
						$(this).animate({ height: 'hide', opacity: 0}, 'fast');
						$label.animate({ height: 'show', opacity: 1}, 'fast');
						e.preventDefault();
					});
								
				
				
				$textarea.focus();
				$textarea.setCursorPosition($textarea.val().length,1);
				
				
			});
		}
		else
		{
			$("#newElementCommentMessage", $clone).disableSelection();
		}

		
	}
	
	$clone.attr('invalidate', 0);
	
	//newElementPic
	$("#newElementCommentTime", $clone).html($.createdAt(comment.CreateDate));
	
	$("#newElementCommentUserName", $clone).html(comment.Name);
		
	$("#newElementCommentMessage", $clone).html(comment.Message);
	
	
	return $clone;
}

$.news.refresh = function()
{
	//TODO:or editing
	if($('#scrollableAreaContent> #newElementsArea').offset().top != 50)
		return;
			
		
	if(!$.news.olderCombinationId)
		$.news.olderCombinationId = 0;
		
	if(!$.news.newerCombinationId)
		$.news.newerCombinationId = 0;

	$.post("./bus/refresh_new_elements.php", 
		"olderCombinationId=" + $.news.olderCombinationId +
		"&newerCombinationId=" + $.news.newerCombinationId,
		function(data)
		{
			$(".newElement, .newElementComment").attr('invalidate', 1);
	
			for(var item in data.Elements)
				$.news.createNewElement(data.Elements[item], 0);
				
			$(".newElement[invalidate=1], .newElementComment[invalidate=1]").not('.newElementShowAll').animate({ height: 'hide', opacity: 0}, 'fast');
		});
}



$.news.suggest.prepare = function()
{

	$.post("./bus/load_tags.php", null, function(data)
	{
		$.news.suggest.tags = data.Tags;
		availableTags = $.news.suggest.tags;
	});

	var availableTags = [];
		
		
		
		function split( val ) {
			return val.split( /,\s*/ );
		}
		function extractLast( term ) {
			return split( term ).pop();
		}
		
	$.news.suggest.window = $("#SuggestElementsArea").clone();
	
	$("#newElementName").keypress($.news.suggest.pressElementName);
	
	$("#newElementInputTags")
	.keypress($.news.suggest.pressElementName)
	.bind( "keydown", function( event ) {
				if ( event.keyCode === $.ui.keyCode.TAB &&
						$( this ).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				minLength: 0,
				source: function( request, response ) {
					// delegate back to autocomplete, but extract the last term
					response( $.ui.autocomplete.filter(
						availableTags, extractLast( request.term ) ) );
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					return false;
				}
			});



			
	$("#SuggestElementsNewElement").toggle(function()
	{
		$("#ProductArea").animate({ height:'show', opacity: 1}, 'fast');		
		$("#SuggestElementsInputElements").animate({ height:'hide', opacity: 1}, 'fast');		
		
	},
	function()
	{
		$("#ProductArea").animate({ height:'hide', opacity: 0}, 'fast');		
		$("#SuggestElementsInputElements").animate({ height:'show', opacity: 1}, 'fast');		
	});
	
	
	$("#SuggestElementsAreaIcon").toggle(function()
	{
		$("#SuggestElementsArea").animate({ height:'show', opacity: 1}, 'fast');		
		
	},
	function()
	{
		$("#SuggestElementsArea").animate({ height:'hide', opacity: 0}, 'fast');		
	});
}

$.news.suggest.set = function($element, $target)
{
		
	$("#SuggestElementsAread1").html($element.html()).
		attr('elementId', $element.attr('elementId'));
	
	$("#SuggestElementsAread2").html($target.html()).
		attr('elementId', $target.attr('elementId'));
	
	$("#SuggestElementsAreaIcon").fadeIn();
	


}

$.news.suggest.pressElementName = function(e)
{
	if(e.which == 13)
	{
		$.news.suggestNewElement($(this));
		e.preventDefault();
	}
};

})(jQuery);
